const Actions = require('./actions');
const DB = require('app/db');
import { monStorage, Storage } from 'clientConfig/util/StoreData';
import { NEW, RUNNING, TERMINATED, COMPLETED, CANCELED } from 'clientConfig/constants'
import { getTime, getIntervalTime } from 'clientConfig/util/queryurlfield';
import { debug } from 'util';
module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {
        head: {},
        item: {},
        content: [],
        process_id: '',
        tool: '',
        finish_time: '',
        process_result: '',
        next_cursor: 0,
        attachment: [],
        proj_name: '',
        proj_num: '',
        cc_list: '',
        folder_id: '',
        originator_user_id: "",
        form_component_values: {}//表单数据

    },

    onFetch: function (params, cb) {
        DB.Proj.get_payment_overview({
            process_id: params,
            unionid: Storage.get('user.unionid')
        }).then((content) => {
            this.data.payPointerCurrNum = content.list[0].payPointerCurrNum;
            this.data.paypointerNum = content.list[0].paypointerNum;
            this.updateComponent()
        }).catch((error) => {
            cb && cb(t.data);
        });
    },
    onQuery: function (params, cb) {
        let t = this;
        t.data.process_id = params.process_id;
        // this.data.tool = t.data.tool;
        DB.Approval.get_approval_detail({ process_id: params.process_id })
            .then((content) => {
                this.data.form_component_values = content.form_component_values;
                //审批单审批发起人信息
                let statue = "";
                // content.approvers = typeof content.approvers == 'string' ? [content.approvers] : content.approvers;
                content.approvers_id = typeof content.approvers_id == 'string' ? [content.approvers_id] : content.approvers_id;
                // debugger
                if (Storage.get('user.id') == content.approvers_id[content.next_cursor] && (content.status == NEW || content.status == RUNNING)) {
                    t.data.tool = true;
                } else {
                    t.data.tool = false;
                }
                this.data.proj_name = content.proj_name;
                this.data.proj_num = content.proj_num;
                this.data.cc_list = content.cc_list;
                this.data.folder_id = content.folder_id;
                this.data.originator_user_id = content.originator_user_id;
                // content.create_time = content.create_time.replace(/\-/g, "\/");
                if (params.origin.includes("pending")) {
                    if (t.data.tool) {
                        statue = "等待我审批"
                    } else {
                        statue = content.status == COMPLETED ? "审批通过" : (content.status == TERMINATED ? "审批拒绝" : (content.status == RUNNING || content.status == NEW ? "审批中" : "已撤销"))
                    }
                } else if (params.origin.includes("sponsored")) {
                    let curent = typeof content.approvers == 'string' ? content.approvers : content.approvers[parseInt(content.next_cursor)]
                    statue = content.status == COMPLETED ? "审批通过" : (content.status == TERMINATED ? "审批拒绝" : (content.status == CANCELED ? "已撤销" : `${curent}审批中`))
                } else if (params.origin.includes("copy")) {
                    statue = "审批通过"
                } else {
                    let curent = typeof content.approvers == 'string' ? content.approvers : content.approvers[parseInt(content.next_cursor)]
                    statue = content.status == COMPLETED ? "审批通过" : (content.status == TERMINATED ? "审批拒绝" : (content.status == CANCELED ? "已撤销" : `${curent}审批中`))
                }
                this.data.head = { name: content.originator_user, statue: statue };
                //debugger
                //审批流程人员信息               
                try {
                    this.approvals = JSON.parse(content.approvers);
                    this.finish_time = JSON.parse(content.finish_time);
                } catch (e) {
                    this.approvals = content.approvers;
                    this.finish_time = content.finish_time;
                }
                this.process_result = content.process_result;
                var approvers = [];//存储每一级审批的审批人信息
                // debugger
                if (!(this.approvals instanceof Array)) {
                    var obj = {};
                    obj.ender = this.approvals;
                    obj.statue = content.status == COMPLETED ? "已同意" : (content.status == TERMINATED ? "已拒绝" : (content.status == CANCELED ? "已撤销" : `审批中`))
                    obj.process_result = typeof this.process_result == 'string' ? JSON.parse(this.process_result) : this.process_result;
                    if (obj.statue == "审批中") {
                        obj.end_date = '已等待' + getIntervalTime(new Date(getTime()).valueOf() - new Date(content.create_time).valueOf());
                    } else {
                        obj.end_date = content.finish_time;
                    }
                    approvers.push(obj)
                } else {
                    let next_cursor = parseInt(content.next_cursor);
                    for (let i = 0; i < this.approvals.length; i++) {
                        var obj = {};
                        obj.ender = this.approvals[i];
                        try {
                            obj.process_result = JSON.parse(this.process_result[i]);
                        } catch (e) {
                            obj.process_result = { content: "", file: "", imgae: "" }
                        }
                        // obj.process_result = JSON.parse(this.process_result[i]);
                        if (next_cursor < i) {
                            obj.statue = "";
                            obj.end_date = "";
                        } else if (next_cursor == i) {
                            obj.statue = content.status == TERMINATED ? "已拒绝" : (content.status == CANCELED ? "已撤销" : (content.status == COMPLETED ? "已同意" : `审批中`))
                            if (obj.statue == "审批中") {
                                if (next_cursor > 0) {
                                    if (this.finish_time instanceof Array) {
                                        obj.end_date = '已等待' + getIntervalTime(new Date(getTime()).valueOf() - (new Date(this.finish_time[next_cursor - 1]).valueOf()));
                                    } else {
                                        obj.end_date = '已等待' + getIntervalTime(new Date(getTime()).valueOf() - (new Date(this.finish_time).valueOf()));
                                    }
                                } else {
                                    obj.end_date = '已等待' + getIntervalTime(new Date(getTime()).valueOf() - new Date(content.create_time).valueOf());
                                }
                            } else if (obj.statue) {
                                // console.log(content.finish_time[i])
                                if(content.finish_time instanceof Array){
                                    obj.end_date = this.finish_time[i];
                                }else{
                                    obj.end_date = this.finish_time
                                }
                            }
                        } else if (next_cursor > i) {
                            if (this.approvals[i] == this.approvals[i + 1]) {
                                obj.statue = "已评论";
                            } else {
                                obj.statue = "已同意";
                            }

                            if (this.finish_time instanceof Array) {
                                obj.end_date = this.finish_time[i];
                            } else {
                                obj.end_date = this.finish_time;
                            }
                        }
                        approvers.push(obj)
                    }
                }
                this.data.item = { sender: content.originator_user, begin_date: content.create_time, approvers }
                //审批单内容
                this.data.content = [];
                var value = {};
                value.badge = false;
                value.title = content.proj_name;
                value.subtitle = "";
                value.content = [];
                let attachment = [];
                let process = { "subcontent": "审批编号", "unitcontent": content.process_id };
                let proj = { "subcontent": "项目单号", "unitcontent": content.proj_num };
                value.content[0] = process;
                value.content[1] = proj;
                let nodes = content.form_component_values.nodelists;
                // debugger
                if ((params.origin.includes("changerecord") || content.proj_category == "changereq") && (content.status != CANCELED)) {
                    let type = { "subcontent": "变更类型", "unitcontent": JSON.parse(content.form_component_values.content.changerecord_type).type };
                    let old_process_id = { "subcontent": "审批编号", "unitcontent": JSON.parse(content.form_component_values.content.changerecord_type).old_process_id };
                    let old_proj_category = JSON.parse(content.form_component_values.content.changerecord_type).old_proj_category;
                    value.content[2] = type;
                    value.content[3] = old_process_id;
                    for (let i = 0; i < nodes.length; i++) {
                        for (let j = 0; j < nodes[i].node_info.length; j++) {
                            if (nodes[i].node_info[j].ext_value) {
                                let n = 1;
                                do {
                                    var obj = {};
                                    obj.subcontent = n == 1 ? "变更前" : "变更后";
                                    if (nodes[i].node_info[j].name == "上传附件") {
                                        let data_arr1 = null;
                                        let data_arr = JSON.parse(nodes[i].node_info[j].ext_value);
                                        try {
                                            data_arr1 = nodes[i].node_info[j].value instanceof Array ? nodes[i].node_info[j].value : [];
                                        } catch (e) {
                                            data_arr1 = JSON.parse(nodes[i].node_info[j].value);
                                        }
                                        let text = '';
                                        let text1 = '';
                                        for (let item of data_arr) {
                                            text = text ? text + ',' + item.fileName : item.fileName;
                                        }
                                        if (data_arr1.length > 0) {
                                            for (let item of data_arr1) {
                                                text1 = text1 ? text1 + ',' + item.fileName : item.fileName;
                                            }
                                        }
                                        obj.unitcontent = (old_proj_category == 'software' && j == 0 ? nodes[i].node_info[j].name : nodes[i].node_info[j].name + "_") + (n == 1 ? text : text1);
                                    } else {
                                        obj.unitcontent = (old_proj_category == 'software' && j == 0 ? nodes[i].node_info[j].name : nodes[i].node_info[j].name + "_") + (n == 1 ? nodes[i].node_info[j].ext_value : nodes[i].node_info[j].value);
                                    }
                                    if (obj.subcontent == "上传附件") {
                                        this.data.attachment = obj.unitcontent;
                                        continue;
                                    }
                                    value.content.push(obj);
                                    n++;
                                } while (n < 3);
                            }
                        }
                    }
                } else if (content.proj_category == 'software' || (content.form_component_values.content.changerecord_type && JSON.parse(content.form_component_values.content.changerecord_type).hasOwnProperty("old_type") && JSON.parse(content.form_component_values.content.changerecord_type).old_type == "software")) {
                    //content.proj_category == 'tenderplan' || content.proj_category == 'software' || (content.form_component_values.content.changerecord_type && JSON.parse(content.form_component_values.content.changerecord_type).hasOwnProperty("old_type") && (JSON.parse(content.form_component_values.content.changerecord_type).old_type == "software" || JSON.parse(content.form_component_values.content.changerecord_type).old_type == "tenderplan"))) {
                    //    debugger
                    for (let i = 0; i < nodes.length; i++) {
                        for (let j = 0; j < nodes[i].node_info.length; j++) {
                            var obj = {};
                            obj.subcontent = content.proj_category == 'software' && i == 0 ? nodes[i].node_name : nodes[i].node_name + "-" + nodes[i].node_info[j].name;
                            obj.unitcontent = nodes[i].node_info[j].value;
                            if (obj.subcontent == "上传附件") {
                                attachment = obj.unitcontent;
                                continue;
                            }
                            value.content.push(obj)
                        }
                    }
                    //添加附件
                    if (content.form_component_values.content.attach_info) {
                        attachment = JSON.parse(content.form_component_values.content.attach_info)
                    }
                } else if (content.proj_category == "faultreq") {
                    value.content[0] = { "subcontent": "故障编号", "unitcontent": content.process_id }
                } else {
                    // for (let i = 0; i < nodes.length; i++) {
                    //     for (let j = 0; j < nodes[i].node_info.length; j++) {
                    //         var obj = {};
                    //         obj.subcontent = j == 0 ? nodes[i].node_name : nodes[i].node_name + "-" + nodes[i].node_info[j].name;
                    //         obj.unitcontent = nodes[i].node_info[j].value;
                    //         if (obj.subcontent == "上传附件") {
                    //             attachment = obj.unitcontent;
                    //             continue;
                    //         }
                    //         value.content.push(obj)
                    //     }
                    // }
                    for (let i = 0; i < nodes.length; i++) {
                        for (let j = 0; j < nodes[i].node_info.length; j++) {
                            var obj = {};
                            obj.subcontent = nodes[i].node_info[j].name;
                            obj.unitcontent = nodes[i].node_info[j].value;
                            if (obj.subcontent == "上传附件" || obj.subcontent == "上传文件" || obj.subcontent == "上传图片") {
                                try {
                                    attachment = attachment.concat(JSON.parse(obj.unitcontent))
                                } catch (e) {
                                    attachment = attachment.concat(obj.unitcontent);
                                }
                                continue;
                            }
                            value.content.push(obj)
                        }
                    }
                }
                // debugger
                t.data.proj_type = content.proj_category
                t.data.module_type = content.module_type
                t.data.payplanId = content.form_component_values.content.payplanId
                t.data.content.push(value)
                t.data.finish_time = content.finish_time;
                t.data.process_result = content.process_result;
                t.data.next_cursor = content.next_cursor;
                t.data.attachment = attachment;
                t.data.approvers_id = content.approvers_id;
                t.data.cc_list_id = content.cc_list_id;
                if (content.proj_category == 'payreq') {
                    this.onFetch(content.form_component_values.content.payplanId);
                }
                //Storage.get('user.id') != content.approvers_id[t.data.next_cursor] ||
                //修改tool#warning
                // debugger
                // if (approvers[t.data.next_cursor] && ((content.status != NEW && content.status != RUNNING))) {
                //     this.data.tool = false;
                // }
                t.updateComponent();
            })
            .catch((error) => {
                cb && cb(t.data);
            });
    },
    sendNotice: function (noticed_lists, params) {
        DB.Notice.send_notice.config.query = {
            noticed_lists
        };
        DB.Notice.send_notice(params)
            .then((content) => {
                if (!content) {
                    console.log('成功')
                } else {
                    console.log('失败')
                }
            })
            .catch((error) => {

            });
    },
    updateComponent: function () {
        this.trigger(this.data);
    }
});
